package com.boruan.shengtangfeng.api.controller;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.dao.IUserDao;
import com.boruan.shengtangfeng.core.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.boruan.shengtangfeng.api.jwt.UserSubject;
import com.boruan.shengtangfeng.api.jwt.util.JwtUtil;
import com.boruan.shengtangfeng.core.dto.ArticleCommentDto;
import com.boruan.shengtangfeng.core.dto.ArticleDto;
import com.boruan.shengtangfeng.core.dto.ArticlePageSearch;
import com.boruan.shengtangfeng.core.dto.AttentionDto;
import com.boruan.shengtangfeng.core.dto.UserCategoryDto;
import com.boruan.shengtangfeng.core.dto.mapper.ArticleDtoMapper;
import com.boruan.shengtangfeng.core.service.IAccoladeService;
import com.boruan.shengtangfeng.core.service.IArticleCategoryService;
import com.boruan.shengtangfeng.core.service.IArticleCommentService;
import com.boruan.shengtangfeng.core.service.IArticleService;
import com.boruan.shengtangfeng.core.service.IAttentionService;
import com.boruan.shengtangfeng.core.service.IFavoritesService;
import com.boruan.shengtangfeng.core.service.ILogService;
import com.boruan.shengtangfeng.core.service.IPopularWordsService;
import com.boruan.shengtangfeng.core.service.ISearchWordsService;
import com.boruan.shengtangfeng.core.service.IUserCategoryService;
import com.boruan.shengtangfeng.core.service.IUserService;
import com.boruan.shengtangfeng.core.service.IVideoCategoryService;
import com.boruan.shengtangfeng.core.utils.CommentUtil;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.utils.StringUtils;
import com.boruan.shengtangfeng.core.vo.ArticleCategoryVo;
import com.boruan.shengtangfeng.core.vo.ArticleCommentVo;
import com.boruan.shengtangfeng.core.vo.ArticleUserCategoryVo;
import com.boruan.shengtangfeng.core.vo.ArticleVo;
import com.boruan.shengtangfeng.core.vo.PopularWordsVo;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCategoryVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleCommentVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.ArticleVoMapper;
import com.boruan.shengtangfeng.core.vo.mapper.PopularWordsMapper;
import com.google.common.base.Strings;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author KongXH
 * @title: sss
 * @projectName ShengTangFeng-V2-JAVA
 * @description: TODO
 * @date 2020/8/1210:50
 */

@Slf4j
@RestController
@SuppressWarnings("all")
@RequestMapping("/api/article")
@Api(value = "", tags = { "NO:3 国风相关接口" })
public class ArticleApi {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IArticleCommentService articleCommentService;
    @Autowired
    private IUserCategoryService userCategoryService;
    @Autowired
    private IVideoCategoryService videoCategoryService;
    @Autowired
    private IArticleCategoryService articleCategoryService;
    @Autowired
    private IPopularWordsService popularWordsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IAttentionService attentionService;
    @Autowired
    private IFavoritesService favoritesService;
    @Autowired
    private IAccoladeService accoladeService;
    @Autowired
    private ILogService sysLogService;
    @Autowired
    private ISearchWordsService searchWordsService;
    @Autowired
    private IUserDao userDao;


    /**
     * @description: 搜索结果页
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/18 13:39
     */
    @GetMapping("/getUserCategory")
    @ApiOperation(value = "NO:3-1 获取用户的文章类别", notes = "")
    public GlobalReponse<PageQuery<List<ArticleCategoryVo>>> getUserCategory() {
        UserSubject userSubject=JwtUtil.getCurrentJwtUser();
        List<ArticleCategoryVo> vos;
        if(userSubject==null) {
            List<ArticleCategory> articleCategoryList = articleCategoryService.getList(new ArticleCategory());
            vos= ArticleCategoryVoMapper.MAPPER.toVo(articleCategoryList);
        }else {
            List<ArticleCategory> userCategoryList = userCategoryService.getUserArticleCategory(userSubject.getId());
            vos= ArticleCategoryVoMapper.MAPPER.toVo(userCategoryList);
        }
        ArticleCategoryVo vo=new ArticleCategoryVo();
        vo.setId(0L);
        vo.setName("关注");
        vos.add(0, vo);
        return GlobalReponse.success(vos);
    }
    /**
     * @description: 国学文章展示页
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:57
     */
    @PostMapping("/articlePage")
    @ApiOperation(value = "NO:3-2 国学文章分页展示,搜索也可用这个接口", notes = "")
    public GlobalReponse<PageQuery<ArticleVo>> articlePage(@RequestBody ArticlePageSearch articlePageSearch) {
        Article search=new Article();
        PageQuery<Article> pageQuery = new PageQuery<Article>();
        List<Article> list= null;
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        search.set("keyword", articlePageSearch.getKeyword());
        search.setStatus(1);
        if(userSubject!=null&&StringUtils.isNotBlank(articlePageSearch.getKeyword())) {
            searchWordsService.addSearchWord(userSubject.getId(), 2, articlePageSearch.getKeyword());
        }
        if(userSubject!=null) {
            search.set("searchNoBlack", userSubject.getId());
        }
        search.setStatus(1);
        pageQuery.setPageNumber(articlePageSearch.getPageNo());
        //查看我已经关注的分类
        if(articlePageSearch.getCategoryId()!=null&&0 == articlePageSearch.getCategoryId()){
            //用户没登录显示全部
            if(userSubject==null) {
                search.setCategoryId(null);
                articleService.pageQuery(pageQuery, search);
                list = pageQuery.getList();
            }else {
                articleService.pageAttentionArticle(pageQuery, userSubject.getId());
                list = pageQuery.getList();
                if(list.size() <= 0){//没有关注显示全部
                    pageQuery = new PageQuery<Article>();
                    pageQuery.setPageNumber(articlePageSearch.getPageNo());
                    search.setCategoryId(null);
                    articleService.pageQuery(pageQuery, search);
                    list = pageQuery.getList();
                }
            }
        }else{
            search.setCategoryId(articlePageSearch.getCategoryId());
            articleService.pageQuery(pageQuery, search);
            list=pageQuery.getList();
        }

        List<ArticleVo> vos=ArticleVoMapper.MAPPER.toVo(list);
        vos.forEach(vo->{
            if(StringUtils.isNotBlank(vo.getImages())) {
                vo.setImageList(StringUtils.split(vo.getImages(),","));
            }else {
                vo.setImageList(new String[] {});
            }
        });


        pageQuery.setList(vos);

        return GlobalReponse.success(pageQuery);
    }

//    /**
//     * @description: 搜索结果页
//     * @Param
//     * @return
//     * @author KongXH
//     * @date 2020/8/18 13:39
//     */
//    @GetMapping("/search")
//    @ApiOperation(value = "m3 搜索结果页", notes = "")
//    public GlobalReponse<PageQuery<ArticleVo>> search(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
//                                                      @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,Article article) {
//        PageQuery<Article> pageQuery = new PageQuery<Article>();
//        pageQuery.setPageNumber(pageNo);
//        articleService.pageQuery(pageQuery, article);
//        List<Article> list=pageQuery.getList();
//        List<ArticleVo> vos=ArticleVoMapper.MAPPER.toVo(list);
//        vos.forEach(vo->{
//            if(StringUtils.isNotBlank(vo.getImages())) {
//                vo.setImageList(StringUtils.split(vo.getImages(),","));
//            }else {
//                vo.setImageList(new String[] {});
//            }
//        });
//
//
//        pageQuery.setList(vos);
//
//        return GlobalReponse.success(pageQuery);
//    }
    


    /**
     * @description:获取文章详情和评论
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:52
     */
    @GetMapping("/articleDetail/{articleId}")
    @ApiOperation(value = "NO:3-3 获取文章详情", notes = "")
    public GlobalReponse<ArticleVo> detailArticle(@PathVariable("articleId") Long articleId) {
        UserSubject userSubject= JwtUtil.getCurrentJwtUser();

        Article article = articleService.findById(articleId);
        //获取一次详情加一次阅读量
        article.setReadNum((article.getReadNum()==null?0:article.getReadNum())+1);
        articleService.save(article);
        //是否关注
        Attention attention = null;
        //是否收藏
        Favorites favorites = null;
        //是否点赞
        Accolade accolade = null;
        List<ArticleComment> comments;
        if(userSubject!=null) {
            //是否关注
            attention = attentionService.findByFocusId(userSubject.getId(),article.getPublishId());
            //是否收藏
            favorites = favoritesService.getFavorites(userSubject.getId(),articleId,1);
            //是否点赞
            accolade = accoladeService.getAccolade(userSubject.getId(),articleId,1);
            comments = articleCommentService.findByArticleId(userSubject.getId(),articleId, 1);
        }else {
            comments = articleCommentService.findByArticleId(null,articleId, 1);
            
        }



        List<ArticleCommentVo> commentVos= ArticleCommentVoMapper.MAPPER.toVo(comments);
//        commentVos.forEach(vo->{
//            vo.setThumbUpEd(articleCommentService.isThumbUp(vo.getId(), userSubject.getId()));
//        });

        ArticleVo vo= ArticleVoMapper.MAPPER.toVo(article);
        vo.setIsAttention(null == attention ? false:true);
        vo.setIsFavorites(null == favorites ? false:true);
        vo.setIsLike(null == accolade ? false:true);
        vo.setComment(commentVos);
        User user = userDao.unique(article.getPublishId());
        vo.setAccount(user.getAccount());
        return GlobalReponse.success(vo);
    }


    /**
     * @description: 发布文章加载类别
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:52
     */
    @GetMapping("getArticleCategory")
    @ApiOperation(value = "NO:3-4 发布时获取所有文章类别", notes = "")
    public GlobalReponse<List<ArticleCategoryVo>> getArticleCategory() {
        ArticleCategory articleCategory = new ArticleCategory();
        List<ArticleCategory> list=articleService.getCategoryList(articleCategory);
        ArrayList<ArticleCategory> articleCategories = new ArrayList<>();
        for (ArticleCategory category : list) {
            if (!category.getName().equals("全部")){
                articleCategories.add(category);
            }
        }
        return GlobalReponse.success(ArticleCategoryVoMapper.MAPPER.toVo(articleCategories));
    }

    /**
     * @description: 保存文章
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/12 15:52
     */
    @PostMapping("saveArticle")
    @ApiOperation(value = "NO:3-4 发布文章", notes = "新增、修改保存")
    public GlobalReponse saveArticle(@RequestBody ArticleDto articleDto) throws IOException {

        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Document doc = Jsoup.parse(articleDto.getContent());
        Elements pngs = doc.select("img[src]");// 所有引用图片的元素
        String images = "";
        for (int i = 0; i < pngs.size(); i++) {
            Element element = pngs.get(i);
            if(i==0) {
                images = images + element.attr("src");
            }else {
                images = images +"," + element.attr("src");
            }
        }
        if(articleDto.getId()!=null) {
            Article article=articleService.findId(articleDto.getId());
            if(StringUtils.equals(article.getTitle(),articleDto.getTitle())) {
                //标题没变不用检测
            }else {
                Article search=new Article();
                search.setTitle(articleDto.getTitle());
                search.setIsDeleted(false);
                List<Article> old=articleService.findByTemplate(search);
                if(old!=null&&old.size()>0) {
                    return GlobalReponse.fail("该标题已经存在，请修改后发布");
                }
            }
            //update by 刘光强 2022年1月22日13:08:58 去掉审核
            article.setStatus(1);
//            article.setStatus(0);
            article.setCategoryId(articleDto.getCategoryId());
            article.setContent(articleDto.getContent());
            article.setTitle(articleDto.getTitle());
            article.setType(Strings.isNullOrEmpty(article.getImages()) ? 1 : article.getImages().split(",").length == 1 ? 2 : 3);
            article.setSummary(StringUtils.dealContent(article.getContent()));
            article.setImages(images);
            article.setUploadType(1);
            articleService.save(article);
        }else {
            Article search=new Article();
            search.setTitle(articleDto.getTitle());
            search.setIsDeleted(false);
            List<Article> old=articleService.findByTemplate(search);
            if(old!=null&&old.size()>0) {
                return GlobalReponse.fail("该标题已经存在，请修改后发布");
            }
            Article article=ArticleDtoMapper.MAPPER.toEntity(articleDto);
            article.setImages(images);
            article.setUploadType(1);
            article.setPublishId(userSubject.getId());
            article.setPublisher(userSubject.getName());
            article.setPublisherIcon(userSubject.getIcon());
            article.setCreateBy(userSubject.getName());
            article.setCreateTime(new Date());
            article.setPublishDate(new Date());
            //update by 刘光强 2022年1月22日13:08:58 去掉审核
            article.setStatus(1);
//            article.setStatus(0);
            article.setReadNum(0);
            article.setCommentNum(0);
            article.setThumpUpNum(0);
            article.setRecommend(false);
            article.setIsDeleted(false);
            article.setType(Strings.isNullOrEmpty(article.getImages()) ? 1 : article.getImages().split(",").length == 1 ? 2 : 3);
            article.setSummary(StringUtils.dealContent(article.getContent()));
            articleService.save(article);
        }
        return GlobalReponse.success("发布成功");
    }

    /**
     * @description: 展示我的类别
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/13 14:15
     */
    @PostMapping("getMyCategory")
    @ApiOperation(value = "NO:3-4 编辑我的类别选择详情", notes = "")
    public GlobalReponse<List<ArticleUserCategoryVo>> getMyCategory() {
        UserSubject userSubject=JwtUtil.getCurrentJwtUser();
        ArticleCategory articleCategory =new ArticleCategory();
        List<ArticleCategory> allArticleCategoryList =articleService.getCategoryList(articleCategory);//文章全部类别
        ArrayList<ArticleCategory> articleCategories = new ArrayList<>();
        for (ArticleCategory category : allArticleCategoryList) {
            if (!category.getName().equals("全部")){
                articleCategories.add(category);
            }
        }
        List<ArticleCategory> userArticleCategoryList =userCategoryService.getUserArticleCategory(userSubject.getId());//已选全部类别
        List<ArticleCategory> notChoiceArticleCategoryList=new ArrayList<>();
        CollectionUtils.addAll(notChoiceArticleCategoryList, new Object[articleCategories.size()]);
        Collections.copy(notChoiceArticleCategoryList,articleCategories );
        notChoiceArticleCategoryList.removeAll(userArticleCategoryList);
        ArticleUserCategoryVo vo = new ArticleUserCategoryVo();
        vo.setAllArticleCategorie(articleCategories);
        ArticleCategory ac=new ArticleCategory();
        ac.setId(0L);
        ac.setName("关注");
        userArticleCategoryList.add(0, ac);
        vo.setUserArticleCategorie(userArticleCategoryList);
        vo.setNotChoiceArticleCategorie(notChoiceArticleCategoryList);
        return GlobalReponse.success(vo);
    }

    /**
     * @description: 保存我的类别
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/13 14:01
     */
    @PostMapping("saveUserCategory")
    @ApiOperation(value = "NO:3-7 保存我的类别", notes = "")
    public GlobalReponse saveUserCategory(@RequestBody UserCategoryDto userCategoryDto) {
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        userCategoryService.saveUserCategory(userCategoryDto,1,userSubject.getId());

        return GlobalReponse.success();
    }



    /**
     * @description: 保存收藏
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/17 14:15
     */
    @PostMapping("/saveArticleFavorites/{articleId}")
    @ApiOperation(value = "NO:3-8 收藏/取消收藏文章，data是true是收藏成功，false是取消收藏成功", notes = "")
    public GlobalReponse<Boolean> saveFavorites(@PathVariable Long articleId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        Favorites favorites=new Favorites();
        favorites.setArticleId(articleId);
        favorites.setType(1);
        favorites.setUserId(user.getId());
        favorites.setCreateBy(user.getName());
        favorites.setCreateTime(new Date());
        return favoritesService.saveFavorites(favorites);
    }



    /**
     * @description: 保存点赞
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/17 17:32
     */
    @PostMapping("saveAccolade/{articleId}")
    @ApiOperation(value = "NO:3-9 点赞/取消点赞文章，data是true是点赞成功，false是取消点赞成功", notes = "")
    public GlobalReponse<Boolean> saveAccolade(@PathVariable Long articleId) {
        UserSubject user = JwtUtil.getCurrentJwtUser();
        Accolade accolade=new Accolade();
        accolade.setArticleId(articleId);
        accolade.setType(1);
        accolade.setUserId(user.getId());
        accolade.setCreateBy(user.getName());
        accolade.setCreateTime(new Date());
        return accoladeService.saveAccolade(accolade);
    }


    /**
     * @description: 获取关键词
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/13 17:10
     */
    @PostMapping("getPopularWords")
    @ApiOperation(value = "NO:3-10 获取文章热门词 ", notes = "")
    public GlobalReponse<List<PopularWordsVo>> getPopularWords() {
//        关键字类型1试题2文3视频
        List<PopularWords> popularWordsList = popularWordsService.getList(2);
        return GlobalReponse.success(PopularWordsMapper.MAPPER.toVo(popularWordsList));
    }


    /*

     **
     * @description: 获取邀请码
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/14 14:18
     *//*

    @GetMapping("getAttention")
    @ApiOperation(value = "m3-获取邀请码", notes = "")
    public GlobalReponse<List<UserVo>> getAttention(Long id){
        User user = userService.findByInvitationCode(id);
        return GlobalReponse.success(UserVoMapper.MAPPER.toVo(user));

    }
*/


    /**
     * @description: 保存关注
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/14 13:53
     */
    @PostMapping("saveAttention")
    @ApiOperation(value = "NO:3-11 关注/取消关注，data是true是关注成功，false是取消关注成功", notes = "")
    public GlobalReponse<Boolean> saveAttention(@RequestBody AttentionDto dto){
        Attention attention = new Attention();
        UserSubject user = JwtUtil.getCurrentJwtUser();
        //关注信息保存
        attention.setUserId(user.getId());
        attention.setFocusUserId(dto.getFocusUserId());
        attention.setIsDeleted(false);
        return attentionService.saveAttention(attention,dto.getInvitationCode());
    }





    /**
     * @description: 文章评论
     * @Param
     * @return
     * @author KongXH
     * @date 2020/8/14 16:34
     */
    @PostMapping(value="/articleComment")
    @ApiOperation(value = "NO:3-12 文章评论", notes = "")
    public GlobalReponse<ArticleCommentVo> articleComment(@RequestBody ArticleCommentDto articleCommentDto) {
        GlobalReponse globalReponse = null;
        UserSubject userSubject = JwtUtil.getCurrentJwtUser();
        Article article=articleService.findId(articleCommentDto.getArticleId());
        ArticleComment comment = new ArticleComment();

        Integer check= CommentUtil.checkComment(articleCommentDto.getContent());
        if(check==2) {
            comment.setStatus(1);
            globalReponse=GlobalReponse.success(ArticleCommentVoMapper.MAPPER.toVo(comment));
            //TODO 评论数审核过再加1
            article.setCommentNum((article.getCommentNum()==null?0:article.getCommentNum())+1);
            articleService.save(article);
        }else if(check==1){
            comment.setStatus(0);
            globalReponse=GlobalReponse.fail("您的评论包含敏感词，需要等待客服审核");
        } else if(check==0){
            return GlobalReponse.fail("您的评论包含敏感词禁止评论");
        }
        comment.setContent(articleCommentDto.getContent());
        comment.setCreateBy(userSubject.getMobile());
        comment.setCreateTime(new Date());
        comment.setIsDeleted(false);
        comment.setArticleId(articleCommentDto.getArticleId());
        comment.setUserId(userSubject.getId());
        comment.setUserName(userSubject.getName());
        comment.setUserIcon(userSubject.getIcon());
        articleCommentService.save(comment);
        return globalReponse.setData(ArticleCommentVoMapper.MAPPER.toVo(comment));
    }
}
